ggplot2

The grammar of graphics: consistent aesthetics, multidimensional conditioning, and step-by-step plot building.

library(ggplot2)

alt text


alt text

p <- ggplot(mpg, aes(x=hwy, y=cty))
p + geom_point()


alt text

Simple scatterplot

p <- ggplot(mtcars, aes(x=wt, y=mpg))
p + geom_point()

Add aesthetic mappings

Set color by # of cylinders

p + geom_point(aes(colour = factor(cyl)))


Set shape using # of cylinders

p + geom_point(aes(shape = factor(cyl)))


Adjust size by qsec

p + geom_point(aes(size = qsec))


Add a linear model

p + geom_point() + geom_smooth(method="lm")


Change scale color

p + geom_point(aes(colour = cyl)) + scale_colour_gradient(low = "blue")


Change scale shapes

p + geom_point(aes(shape = factor(cyl))) + scale_shape(solid = FALSE)


Set aesthetics to fixed value

ggplot(mtcars, aes(wt, mpg)) + geom_point(colour = "red", size = 3)

Transparancy

Varying alpha is useful for large datasets

d <- ggplot(diamonds, aes(carat, price))
d + geom_point(alpha = 1/10)


d + geom_point(alpha = 1/20)


d + geom_point(alpha = 1/100)

Other Plot types


alt text


alt text


alt text


alt text


alt text


Three Variables

alt text


Stats

Visualize a data transformation

alt text

  • Each stat creates additional variables with a common ..name.. syntax
  • Often two ways: stat_bin(geom="bar") OR geom_bar(stat="bin")

alt text


alt text

Specifying Scales

alt text


Discrete color: default

b=ggplot(mpg,aes(fl))+geom_bar( aes(fill = fl)); b


Discrete color: brewer

b+scale_fill_brewer( palette = "Blues")


Discrete color: greys

b+scale_fill_grey( start = 0.2, end = 0.8, na.value = "red")


Continuous color: defaults

a <- ggplot(mpg, aes(hwy)) + geom_dotplot( aes(fill = ..x..)); a
## stat_bindot: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.


Continuous color: gradient

a + scale_fill_gradient( low = "red", high = "yellow")
## stat_bindot: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.


Continuous color: gradient2

a + scale_fill_gradient2(low = "red", high = "blue", mid = "white", midpoint = 25)
## stat_bindot: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.


Continuous color: gradientn

a + scale_fill_gradientn( colours = rainbow(10))
## stat_bindot: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.

Coordinate Systems

alt text

Position

alt text

Themes

alt text

Colophon

Sources: * ggplot cheatsheet *

Licensing: * Presentation: CC-BY-3.0 * Source code: MIT